<?php
namespace Admin\Controller;

use Util\AccessController;

class SystemController extends AccessController {

    public function Index() {
        $Tables_in = 'Tables_in_' . C('DB_NAME');
        $sql = "show tables";
        $tablesData = M()->query($sql);
        foreach ($tablesData as $key => $value) {
            $tablesData[$key]['table'] = $value[$Tables_in];
            $table_sql = "select `TABLE_NAME` from " . C('DB_PREFIX') . "table where `TABLE`='" . $value[$Tables_in] . "'";
            $tableName = M()->query($table_sql);
            $tablesData[$key]['table_name'] = $tableName[0]['TABLE_NAME'];
            unset($tablesData[$key][$Tables_in]);
            $sql1 = "desc " . $value[$Tables_in];
            $sql2 = "select COLUMN_NAME,COLUMN_COMMENT ,ORDINAL_POSITION from INFORMATION_SCHEMA.Columns  where  table_name='" . $value[$Tables_in] . "'";
            $tablesInfo = M()->query($sql1);
            $comment = M()->query($sql2);
            $temp = array();
            foreach ($comment as $k => $v) {
                if ($v['ORDINAL_POSITION'] == 1) {
                    $t = 0;
                    $temp[$t++] = $v;
                } else {
                    $temp[$t++] = $v;
                }
            }
            $tablesData[$key]['info'] = $tablesInfo;
            foreach ($tablesInfo as $k => $v) {
                $tablesData[$key]['info'][$k]['Comment'] = $temp[$k]['COLUMN_COMMENT'];

            }
            if (substr($value[$Tables_in], -4) == 'view') {
                $tablesData[$key]['table_view'] = 1;
            } else {
                $tablesData[$key]['table_view'] = 0;
            }
        }
        $tablesData = my_sort($tablesData,'table_view',SORT_ASC,SORT_STRING);
        $this->tablesData = $tablesData;
        $this->display();
    }

    public function UpdateTableName() {
        $table_sql = "select `TABLE_NAME` from " . C('DB_PREFIX') . "table where `TABLE`='" . $_POST['TABLE'] . "'";
        $tablesInfo = M()->query($table_sql);
        if ($tablesInfo) {
            $where['TABLE'] = $_POST['TABLE'];
            $savedate['TABLE_NAME'] = $_POST['TABLE_NAME'];
            $update_OK = M('table')->where($where)->save($savedate);
        } else {
            $adddate['TABLE'] = $_POST['TABLE'];
            $adddate['TABLE_NAME'] = $_POST['TABLE_NAME'];
            $Add_OK = M('table')->add($adddate);
        }
        if ($update_OK || $Add_OK) {
            $this->success('修改成功');
        } else {
            $this->error('修改失败');
        }
    }

    //    /*
    //     * 设置默认仓库位置
    //     */
    //
    //    public function SetMrSg(){
    //
    //    }

}